import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateImageDto } from './dto/create-image.dto';
import { UpdateImageDto } from './dto/update-image.dto';
import { ImageSource } from './entities/image.entity'
import { getType } from './enum/Enum';

@Injectable()
export class ImageService {
  constructor(
    @InjectRepository(ImageSource)
    private image: Repository<ImageSource>,
  ) { }

  formatType(result: ImageSource[]) {
    return result.forEach(image => { image.typeDesc = getType(image.type) })
  }

  create(createImageDto: CreateImageDto) {
    return this.image.save(createImageDto)
  }

  async findAll(createImageDto: CreateImageDto) {
    const sql = this.image.createQueryBuilder('i')
    const { guid, refGuid, type } = createImageDto
    sql.where('i.delete = :delete', { delete: false })
    if (guid) {
      sql.andWhere('i.guid = :guid', { guid })
    }
    if (refGuid) {
      sql.andWhere('i.ref_guid = :refGuid', { refGuid })
    }
    if (type) {
      sql.andWhere('i.type = :type', { type })
    }
    sql.orderBy('i.create_time', 'DESC')
    const result = await sql.getMany();
    this.formatType(result)
    console.log('findAll :>> ', sql.getSql())
    return result
  }

  async deleteImageByGuid(hash: string) {
    return this.image.createQueryBuilder().update(ImageSource).set({ delete: true, updateTime: new Date() }).where('hash=:hash', { hash }).execute()
  }
}
